function get_mm_tab_id(mm) {
	return 'tab_mm_' + mm.id;
}	

function get_mm_tab_name(mm) {
	return mm.title == null ? mm.url : mm.title;
}

function init_managed_modules_divs() {
	var content_div = document.getElementById("div_content");
	var managed_modules = dao.loadManagedModules();
	for (var i in managed_modules) {
		var mm = managed_modules[i];
		var div = document.createElement("div");
		div.id = 'mm_' + mm.id;
		div.module_id = mm.id;
		div.mm = mm;
		div.style.width = "100%";
		content_div.appendChild(div);
	}
}

function init_managed_div(tab_id, content_div) {
	if (content_div.module_id == null) {
		error("invalid content_div");
		return;
	}
	var mm = content_div.mm;
	var toolbar = document.createElement("div");
	toolbar.style.width = "100%";
	content_div.appendChild(toolbar);
	if (mm.type == 'ss') {
		var post_area = document.createElement("div");
		post_area.id = 'post_area_' + mm.id;
		post_area.className = 'post_area';
		content_div.appendChild(post_area);
		init_toolbar_ss(mm, toolbar);
	} else {
		init_toolbar_mm(mm, toolbar);
		post_area = document.createElement("table");
		post_area.id = 'post_area_' + mm.id;
		post_area.className = 'post_area';
		content_div.appendChild(post_area);
	}
}

function init_toolbar_mm(mm, toolbar) {
	var refresh = document.createElement("input");
	refresh.type = 'button';
	refresh.value = 'Refresh';
	refresh.onclick = refresh_mm;
	refresh.id = 'refresh_' + mm.id;
	refresh.mm = mm;
	toolbar.appendChild(refresh);
}

function clear_post_area(id) {
	var post_area = document.getElementById("post_area_" + id);
	post_area.innerHTML = "";
}	

function refresh_mm() {
	clear_log();
	var mm = event.srcElement.mm;
	clear_post_area(mm.id);
	var session = new MMThreadSession();
	session.pending.push(url_prefix + mm.url);
	nest.addFood(session, true);
}

function stat_mm() {
	var btn = event.srcElement;
	var mm = event.srcElement.mm;
	if (btn.value == 'Start') {
		clear_log();
		clear_post_area(mm.id);
		if (start_sss(mm))
			btn.value = 'Stop';
	}  else {
		btn.value = 'Start';
		stop_sss(mm);
	}
}

MMThreadSession = function() {
	this.id = new Date().getTime();
	this.pending = new Array();
	this.stop = false;
	this.current_url = null;
	this.to_be_review = new Array();
}

MMThreadSession.prototype.bitten = function() {
	if (this.pending.length > 0) {
		this.current_url = this.pending.shift();
		log(this.current_url);
		return this.current_url;
	} 
	return null;
}

MMThreadSession.prototype.hasMore = function() {
	return this.pending.length > 0 && !this.stop;
}

MMThreadSession.prototype.isFinished = function() {
	return this.stop;
}

MMThreadSession.prototype.digest = function(url, has_error, content) {
	if (has_error) {
		log("error");
		return;
	}
	sis_set_content(url_prefix, content);
	var threads = sis_get_threads();
	var stop = false;
	var cnt = 0;
	for (var i in threads) {
		var thread = threads[i];
		if (thread.isReviewed == false) {
			this.to_be_review.push(thread);
			cnt++;
		}
	}
	if (threads.length == 0) stop = true;
	if (cnt < threads.length * 0.9) stop = true; // if more than 90% of the current page are not reviewed, check next page 
	if (stop == false) {
		var next_page = sis_get_next_page_url();
		this.pending.push(next_page);
	}

}

MMThreadSession.prototype.takeback = function(url) {
	this.pending.push(url);
}

MMThreadSession.prototype.finish = function() {
	this.stop = true;
	log("finished");
	start_review(this);
}

ReviewSession = function(t) {
	this.thread = t;
	this.pending = new Array();
	this.stop = false;
	this.current_url = null;
}

ReviewSession.prototype.bitten = function() {
	if (this.pending.length > 0) {
		this.current_url = this.pending.shift();
		log(this.current_url);
		return this.current_url;
	}
	return null
}

ReviewSession.prototype.hasMore = function() {
	return this.pending.length > 0 && !this.stop;
}

ReviewSession.prototype.isFinished = function() {
	return this.stop;
}

ReviewSession.prototype.digest = function(url, has_error, content) {
	if (has_error) {
		error("error review");
		return;
	}
	sis_set_content(url_prefix, content);
	if (this.thread.url == '') {
		this.thread.url = url;
	}
	if (this.thread.title == '') {
		var title = sis_get_title();
		this.thread.title = title;
	}
	var page = new Page();
	page.url = url;
	page.number = sis_get_page_number();
	page.formhash = sis_get_formhash();
	sis_get_posts(page);
	this.thread.pages.push(page);
	var next_page_url = sis_get_next_page_url();
	if (next_page_url != null)
		this.pending.push(next_page_url);
	else {
		page = this.thread.pages[this.thread.pages.length - 1];
		if (page == null) {
			error("Empty page");
			return;
		}
		while (page.posts != null && page.posts.length == 0) {
			this.thread.pages.splice(this.thread.pages.length - 1, 1);
			page = this.thread.pages[this.thread.pages.length - 1];
		}
		if (page.posts != null) {
			mark_review(page.posts[page.posts.length - 1]);
			add_thread(this.thread);
			for (var i in this.thread.pages) {
				page = this.thread.pages[i];
				for (var j in page.posts) {
					var post = page.posts[j];
					if (post.floor > 1) { // do not check main post
						check_post(post, this.thread);
					}
				}
			}
		}
	}
}

ReviewSession.prototype.takeback = function(url) {
	this.pending.push(url);
}

ReviewSession.prototype.finish = function() {
	this.stop = true;
	log("review finished");
	review_finished();
}

function check_post(post, thread) {
	if (post.floor <= thread.managed_floor) return;
	var content = post.content;
	if (content == null) {
		error("content empty: " + post.id + " " + post.time + " " + post.floor);
		return false;
	}
	var flag = remove_html_tags(post);
	if (!flag) return false;
	var word = null;
	if ((word = check_forbidden_word(content)) != null) {
		add_post(post, 'forbid', word);
		return true;
	}
	if (check_flush(content)) {
		add_post(post, 'flush');
		return true;
	}
	if (check_length(content)) {
		add_post(post, 'length');
		return true;
	}
	if (check_adv(content)) {
		add_post(post, 'adv');
		return true;
	}
	if (check_duplicate(content)) {
		add_post(post, 'duplicate');
		return true;
	}
	if (check_good_content(content)) {
		add_post(post, 'good');
		return true;
	}
	add_post(post, 'ok');
}

function check_duplicate(content) {
	return false;
}

var forbidden = ['顶', '沙发'];
function check_forbidden_word(text) {
	return check_array(text, forbidden);
}

function check_flush(text) {
	var last = text.charAt(0);
	var ccnt = 1;
	var max = 0;
	for (var i = 1; i < text.length; i++) {
		if (text.charAt(i) == last) {
			ccnt++;
		} else {
			if (ccnt > max) {
				max = ccnt;
			}
			ccnt = 1;
		}
		last = text.charAt(i);
	}
	return max > 3;
}

var marks_reg = /[`~!@#$%^&*\(\)\-_=+\[{\]}\\\|;:'"\/?.>,<｀～！@＃¥％⋯⋯—＊（）［｛］｝、｜；：‘“，《。》／？＝＋]/g;
function check_length(text) {
	var tmp = text.replace(marks_reg, '');
	return tmp.length < 10;
}

var adv = ['QQ','qq','出售','交易'];

function check_adv(text) {
	return check_array(text, adv) != null;
}

function check_array(text, ary) {
	for (var i in ary) {
		if (text.indexOf(ary[i]) != -1) {
			return ary[i];
		}
	}
	return null;
}

function check_good_content(text) {
	var tmp = text.replace(marks_reg, '');
	return tmp.length > 100;
}

function remove_html_tags(post, check) {
	if (check == null) check = true;
	var text = post.content;
	var match = null;
	var last_match = null;
	var ccnt = 0; // max continous html tags count, used for emotions count
	var max = 0;
	var smilie = '';
	while ((match = /<[^>]+>/.exec(text)) != null) {
		if (match[0].indexOf("<br") != -1 || match[0].indexOf("br>") != -1) {
			text = text.substring(0, match.index) + text.substring(match.index + match[0].length);
			continue;
		}
		if (match[0].substring(0,2) == '</') {
			// closing tag
			text = text.substring(0, match.index) + text.substring(match.index + match[0].length);
			continue;
		}
		if (last_match != null) { 
			smilie = '';
			if (match[0].indexOf("smilieid") != -1 && last_match[0].indexOf("smilieid") != -1) {
				smilie = match[0];
				var b = smilie.indexOf("smilieid");
				smilie = smilie.substring(b + 10);
				b = smilie.indexOf('"');
				smilie = smilie.substring(0, b);
				ccnt++;
			} else if (match[0] == last_match[0]) {
				ccnt++;
			} else {
				if (ccnt > max)
					max = ccnt;
				ccnt = 1;
			}
		}
		text = text.substring(0, match.index) + (smilie == '' ? '' : ('//' + smilie) ) + text.substring(match.index + match[0].length);
		last_match = match;
	}
	var original = post.content; // foe debug use only
	post.content = text;
	if (max > 3 && check) {
		add_post(post, 'flush');
		return false;
	}
	return true;
}

function mark_review(post) {
	if (post.mark_link == null) return;
	log(post.mark_link);
	var debug = document.getElementById("debug");
	if (!debug.checked) {
		var spider = nest.callSpider();
		spider.eat(url_prefix + post.mark_link, null);
	}
}

var __mm_thread = null;

function start_review(mmthread) {
	__mm_thread = mmthread;
	var thread = __mm_thread.to_be_review.pop();
	review(thread);
}

function review(thread) {
	if (thread == null) return;
	var next_page = thread.managed_page;
	var url = null;
	if (next_page == 0) {
		url = thread.url;
	} else {
		url = get_page_url(thread.url, thread.managed_page);
	}
	if (url == null) {
		error("failed to get page url: " + thread.url + " " + thread.managed_page);
		return;
	}
	var review_session = new ReviewSession(thread);
	review_session.pending.push(url_prefix + url);
	nest.addFood(review_session, true);
}

function get_page_url(url, page) {
	var match = /thread-\d+-/.exec(url);
	if (match == null) return null;
	var tmp = url.substring(match[0].length);
	var idx = tmp.indexOf("-");
	if (idx == -1) return null;
	return match[0] + page + tmp.substring(idx);
}

function review_finished() {
	if (__mm_thread == null) return;
	if (__mm_thread.to_be_review.length == 0) return;
	var thread = __mm_thread.to_be_review.pop();
	review(thread);
}

function add_thread(thread) {
	var contents = document.getElementById("div_content").children;
	var content_div = null;
	for (var i in contents) {
		if (contents[i].style.display == 'block') {
			content_div = contents[i];
			break;
		}
	}
	var module_id = content_div.module_id;
	var post_area = document.getElementById('post_area_' + module_id);
	var post_div = document.createElement("tr");
	post_div.className = 'post_area_tr';
	post_area.appendChild(post_div);
	var span = document.createElement("td");
	span.colspan = 2;
	post_div.appendChild(span);
	var link = document.createElement("a");
	link.href = url_prefix + thread.url;
	link.target = "_blank";
	link.innerText = thread.title;
	span.appendChild(link);
	var page = thread.pages[0];
	var post = page.posts[0];
	if (thread.managed_floor == 0) {
		var input = document.createElement("input");
		input.type = 'text';
		input.value = '发帖辛苦啦!';
		span.appendChild(input);
		add_btn(3, post, span, input);
		add_btn(5, post, span, input);
		add_btn(8, post, span, input);
		add_btn(12, post, span, input);
		add_btn(15, post, span, input);
		add_btn(30, post, span, input);
	}
}

function get_current_mm_id() {
	var contents = document.getElementById("div_content").children;
	var content_div = null;
	for (var i in contents) {
		if (contents[i].style.display == 'block') {
			content_div = contents[i];
			break;
		}
	}
	var module_id = content_div.module_id;
	return module_id;	
}

function get_current_post_area() {
	var module_id = get_current_mm_id();
	var post_area = document.getElementById('post_area_' + module_id);
	return post_area;
}

function add_post(post, reason, reason2) {
	var post_area = get_current_post_area();
	var post_div = document.createElement("tr");
	post_div.className = 'post_area_tr';
	post_area.appendChild(post_div);
	var span = document.createElement("td");
	span.className = "post";
	span.innerText = post.content;
	var link = document.createElement("a");
	link.href = post.url;
	link.target = "_blank";
	link.innerText = 'Link';
	span.appendChild(link);
	post_div.appendChild(span);
	span = document.createElement("td");
	span.className = "post_control";
	post_div.appendChild(span);
	var label = document.createElement("label");
	label.innerText = 'Score:';
	span.appendChild(label);
	var input = document.createElement("input");
	input.type = 'number';
	input.size = '10';
	input.id = 'score';
	var score = input;
	span.appendChild(input);
	label = document.createElement("label");
	label.innerText = 'Reason:';
	span.appendChild(label);
	input = document.createElement("input");
	input.type = 'text';
	input.size = '30';
	input.name = 'reason';
	switch (reason) {
		case 'good':
			input.value = '回复认真，鼓励！';
			break;
		case 'good_post':
			input.value = '发帖辛苦了';
			break;
		case 'flush':
			input.value = '符号灌水－请重新阅读版规';
			break;
		case 'length':
			input.value = '字数不够';
			break;
		case 'forbid':
			input.value = '论坛禁止使用"' + reason2 + '"';
			break;
		case 'duplicate':
			input.value = '复制回复';
			break;
		case 'adv':
			input.value = '论坛禁止广告';
			break;
		default:
			input.value = reason;
			break;
	}
	span.appendChild(input);
	var br = document.createElement("br");
	span.appendChild(br);
	if (reason.length > 4) {
		reason = reason.substring(0, 4);
	}
	switch (reason) {
		case 'good':
			add_btn(2, post, span, input, score);
			add_btn(3, post, span, input, score);
			add_btn(4, post, span, input, score);
			add_btn(5, post, span, input, score);
			add_btn(6, post, span, input, score);
			add_btn(7, post, span, input, score);
			add_btn(8, post, span, input, score);
			break;
	 	default:	
			add_btn(-30, post, span, input, score);
			add_btn(-5, post, span, input, score);
			add_btn(-1, post, span, input, score);
			add_btn(2, post, span, input, score);
			add_btn(3, post, span, input, score);
			add_btn(4, post, span, input, score);
			add_btn(5, post, span, input, score);
			add_btn(6, post, span, input, score);
			add_btn(7, post, span, input, score);
			add_btn(8, post, span, input, score);
			break;
	}
	add_btn('Rate', post, span, input, score);
}

function add_btn(score, post, div, reason, score_input) {
	var btn = document.createElement("input");
	btn.type = 'button';
	btn.className = 'score_btn';
	btn.value = score;
	btn.post = post;
	btn.onclick = post_score;
	btn.reason = reason;
	btn.score = score_input;
	div.appendChild(btn);
}

function post_score() {
	var btn = event.srcElement;
	var post = btn.post;
	if (btn.value == 'Rate') {
		if (btn.score.value != '') {
			rate(post, btn.score.value, 0, 0, 0, 0, 0, '', btn.reason.value);
		} else {
			error("Please enter score");
		}
	} else
		rate(post, btn.value, 0, 0, 0, 0, 0, '', btn.reason.value);
}
